package com.jubao.ejb.dao.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.jboss.ejb3.annotation.LocalBinding;
import org.jboss.ejb3.annotation.RemoteBinding;

import com.jubao.ejb.dao.ProductDaoLocal;
import com.jubao.ejb.dao.ProductDaoRemote;
import com.jubao.ejb.dao.util.DaoConstant;
import com.jubao.ejb.entity.Product;

@Stateless
@LocalBinding(jndiBinding = DaoConstant.ProductDaoLocalJndiName)
@RemoteBinding(jndiBinding = DaoConstant.ContentDaoRemoteJndiName)
public class ProductDaoImpl implements ProductDaoLocal, ProductDaoRemote {
	static Logger logger = Logger.getLogger(ProductDaoImpl.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = -7861568656574099969L;

	@PersistenceContext(unitName = "default")
	protected EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public Product save(Product product) {
		Product c = em.merge(product);
		return c;
	}

	public Product find(String id) {
		Query q = em.createNamedQuery("ProductDao.eql.findProductById").setParameter("id", id).setMaxResults(1)
				.setHint("org.hibernate.cacheable", new Boolean(true));
		//.setHint("org.hibernate.cacheRegion", "/entity/Category/Single")
		List<Product> products = q.getResultList();
		Product result = null;
		if (products != null && products.size() > 0) {
			result = products.get(0);
		}
		return result;
	}

	public Product find(long sysId) {
		return em.find(Product.class, sysId);
	}

	public void deleteProductById(String contentId) {
		// TODO Auto-generated method stub

	}

	public long getProductCount(long supplierSysId) {
		Query q = em.createNamedQuery("ProductDao.eql.getProductCountBySupplierSysId")
				.setParameter("supplierSysId", supplierSysId).setMaxResults(1);
		Long result = (Long) q.getSingleResult();
		return result;
	}

	public List<Product> getProductList(long supplierSysId, int pgno, int pgsize) {
		Query q = em.createNamedQuery("ProductDao.eql.getProductListBySupplierSysId").setParameter("supplierSysId",
				supplierSysId);
		//.setHint("org.hibernate.cacheRegion", "/entity/Category/Single")
		List<Product> products = q.setFirstResult(pgno * pgsize).setMaxResults(pgsize).getResultList();
		return products;
	}

}
